import React from 'react'
import GamePad from './appComponents/GamePad'
import CreateGameBase from './appComponents/CreateGameBase'
import { NavLink } from 'react-router-dom'
import { connect } from 'react-redux'
import NumberPad from './appComponents/NumberPad'
import classnames from 'classnames'
import JoinRuleDialog from './JoinRuleDialog'
import GameConfig from '../reducers/gameconfig'
import './appStyle.less'

const GAME_TYPE = {
  '1': 'BULLFIGHT',
  '2': 'OXFIGHT',
  '3': 'HONGZHONG',
  '5': 'DIANZINIU',
  '4': 'JINHUA',
  '6': 'SANGONG',
  '7': 'HUACHUAN',
  '8': 'RUNFAST',
  '10': 'CSMAHJONG',
  '11': 'PJMAHJONG',
  '13': 'HUZMAHJONG',
  '15': 'SANJINPK'
}

//将state.counter绑定到props的counter
const mapStateToProps = (state) => {
  return {
    userInfo: state.app.userInfo,
    userFinanceInfo: state.app.userFinanceInfo,
    agentLevel: state.app.agentLevel,
    showCreateGame: state.dynamics.showCreateGame,
    currentGame: state.dynamics.currentGame,
    gameData: state.app.gameData,
    crowdJoin: state.app.crowdJoin,
    clubUrl: state.app.clubUrl,
    hallPage: state.app.hallPage,
  }
}
//将action的所有方法绑定到props上
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    openModal: (msg) => dispatch(global.allActions.appActions.openModal(msg))
    // increment: (...args) => dispatch(actions.increment(...args)),
    // decrement: (...args) => dispatch(actions.decrement(...args))
  }
}

class App extends React.Component<any, any> {
  public constructor(props) {
    super(props)
    this.state = {
      showNumberPad: false,
      shuaishuaiCname: classnames({
        pulse: false
      }),
      cluburl: '',
      showJoinRule: false,
      showHomeJoin: false,
      clubMethod: '',
      isAndroid: false,
      crowdJoin: {},
      showAmount: false,
      showQrcodeDialog: false,
      showUploadQrcodeDialog: false,
      uploadQrcodeBase64: ''
    }
  }

  public componentDidMount() {
    this.setState({ cluburl: `${config.pre}/login/weiXin/${Cookies.get('areaCode')}?type=10106` })
    setTimeout(() => {
      let shuaishuaiCname = classnames({
        pulse: true
      })
      this.setState({ shuaishuaiCname })
    }, 1000)

    if(window.navigator) {
      if(window.navigator.appVersion.match(/Android/i)) {
        this.setState({
          isAndroid: true
        })
      }
    }


    new Swiper('.room-swiper-container', {
      // Optional parameters
      direction: 'horizontal',
      loop: false
    })
    util.resetFontSize();
  }

  public componentDidUpdate () {


    if (this.props.crowdJoin && this.state.clubMethod === ''){
      let jsonContent = this.props.crowdJoin.jsonContent;
      let json;
      let str
      if (jsonContent != ''){
        json = JSON.parse(jsonContent);
        let gameType = this.props.crowdJoin.gameType;
        if (GameConfig[gameType]) {
          let gameName = GameConfig[gameType].name;
          str = gameName + ' ';
          Object.keys(json).forEach((item) => {
          if (GameConfig[gameType]) {
            let cf = GameConfig[gameType][item]
            if (cf && cf[json[item]]) {
              str += `${cf[json[item]]} `
            }
            }
          })
        } else {
          str = '暂无玩法'
        }
      } else {
        str = '暂无玩法'
      }

      this.setState({
        clubMethod: str
      })
    }

  }

  public componentWillUnmount() {
    console.log('componentWillUnmount')
  }

  public componentWillMount() {
  }

  preventClick(e) {
    e.preventDefault()
  }


  private closeQrcode() {
    this.setState({showQrcodeDialog: false, showUploadQrcodeDialog: false})
  }

  /**
   * 打开上传
   */
  private openQrcodeDialog() {
    this.setState({
      showUploadQrcodeDialog: true
    });
  }

  private onUploadChange(ev: any) {
    console.warn('onUploadChangeonUploadChangeonUploadChangeonUploadChange')
    let file = ev.target.files[0];
    let fr = new FileReader();
    fr.onload = (res: any) => {
      console.log(res);
      let result = res.target.result;
      this.setState({
        uploadQrcodeBase64: result,
      });
      this.uploadQrcode(result);
    };
    fr.readAsDataURL(file);
  }

  uploadQrcode(picStr: string) {
    const params = {
      extId: this.props.userInfo.uid,
      picStr
    };

    const url = `${config.pre}/media/image/picUp2`;

    const opt = {
      headers: {
        Authorization: Cookies.get('token'),
        'Content-type': 'application/json'
      },
      method: 'POST',
      body: picStr,
    };

    fetchJson(url, opt).then(data => {
      console.error('uploadQrcode', data)

      if (data.result === 0) {
        this.savePayQrcode(data.data);
      } else {
        this.props.openModal('文件上传失败,请重新尝试');
      }
    })
    .catch((err) => {
      this.props.openModal('文件上传失败,请重新尝试');
    });
  }

  savePayQrcode(uri) {
    const params = {
      uri,
      uid: this.props.userInfo.uid,
    };
    const url = `${config.pre}/agent/${Cookies.get('areaCode')}/savepayqr`;
    const opt = {
      headers: {
        Authorization: Cookies.get('token'),
        'Content-type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(params),
    };
    fetchJson(url, opt).then(data => {

      console.error('savePayQrcode', data)
      if (data.result === 0) {
        this.props.openModal(data.message);
        this.setState({
          showUploadQrcodeDialog: false
        });
      } else {
        this.props.openModal(data.message);
      }
    })
    .catch((err) => {
      this.props.openModal('文件上传失败,请重新尝试');
    });
  }

  public render() {
    const { showJoinRule, showHomeJoin, clubName, clubNumber, playMethod,clubMethod, isAndroid} = this.state
    const {crowdJoin} = this.props
    let showCrowd = false
    if(crowdJoin) {
      showCrowd = true
    }
    let mainClass = classnames({
      'is-android': isAndroid,
      'view-page': true,
      'home-view': true,
    })
    return (
      <div className={mainClass}>
        <div className="home-head">
          <img src="img/app/jiutian-hy-text.png" className={this.state.shuaishuaiCname + ' shuaishuai'} alt=""  onClick={this.preventClick.bind(this)}/>
          {/* <img src="img/app/app-head-di.png" {this.props.userInfo.headUrl} alt=""http://c-c.jiahuagame.com/source/icon/cs-majiang.png""  className="full pos-abs" alt=""/> */}
          <div className="info-header">
          <img src="img/app/head-frame.png" className="head-border" onClick={this.preventClick.bind(this)}/>
          <div className="info-content" onClick={this.openQrcodeDialog.bind(this)}>
          <div className="head-img-wrapper">
              <img src="img/app/head-border.png" className="head-border-img" />
              <img src="img/app/head-border-s.png" className="head-border-s" />
              <img src={this.props.userInfo.headUrl} className="head-img" alt="" />
            </div>
            <div className="userinfo-flexbox">
                <div style={{width: '100px'}} className="mlr-0 text-ellipsis header-first pos-relative">
                  {this.props.userInfo.nickname}
                </div>
                <div className="mlr-0 header-lftid pos-relative">ID: {this.props.userInfo.lftid}</div>
            </div>
            <div className="diamond-flexbox pos-relative">
                <span className="info-diamond-num">
                <img className="info-diamond" src="img/app/dimond.png" alt="" />
                <span>{this.props.userFinanceInfo.amount}</span>
                </span>
            </div>
          </div>
          </div>
        </div>
        <div className="home-scene">
          {/*<img src="img/app/yun1.png" className="pos-abs yun1 animated fadeInLeft" alt="" />*/}
          {/* <img src="img/app/yun2.png" className="pos-abs yun2 animated fadeIn" alt="" /> */}
        </div>
        <div className="home-gamepad">
          <GamePad></GamePad>
        </div>

        <div className="home-join room-swiper-container">
          <div className="swiper-wrapper">
            <div className="club-join-container swiper-slide">
              {
                showCrowd ? <div className="home-join-content">
                  <div className="home-join-wrapper">
                    <div className="full pos-relative">
                      {/* <a href={this.state.cluburl}><img src="img/app/group-btn.png" className="btn" alt=""/></a> */}
                      <img src="img/app/lower-frame.png" alt="" className="lower-frame" />
                      <div className="rapid-join-wrapper">
                        <div className="club-head">
                          {/* {crowdJoin.proxyHead} "https://cdn.vuetifyjs.com/images/flags/cn.png" alt="" className="enter-club" /> */}
                          <img src={crowdJoin.proxyHead} alt="" className="enter-club-head" />
                        </div>
                        <div className="club-details">
                          <span>会长: {crowdJoin.proxyName}</span>
                          <span>玩法ID: {crowdJoin.confId}</span>
                          <span className="club-method">游戏: {clubMethod}</span>
                        </div>
                        <a href={crowdJoin.redirectUrl} className="enter-club"><img src="img/app/enter.png" alt="" /></a>

                      </div>
                    </div>
                  </div>
                </div> : <div className="home-join-content">
                    {/* <img src="img/app/join-line.png" className="full-width" alt="" /> */}
                    <div className="pure-g">
                      {/* <div className="pure-u-1-2">
              <img onClick={() => this.setState({showNumberPad: true})} src="img/app/room-join-btn.png" className="btn" alt=""/>
            </div> */}
                      <div className="fill-width rapid-join-flex">
                        <a onClick={() => this.setState({ showJoinRule: true })}><img src="img/app/rapid-join-club.png" className="btn" alt="" /></a>
                      </div>
                    </div>
                  </div>
              }
            </div>
            <div className="room-enter-container swiper-slide">
              {/* <img src="img/app/quick-text.png" className="full-width" alt="" /> */}
              <div className="pure-g">
                <div className="fill-width rapid-join-flex">
                  <a onClick={() => this.setState({ showNumberPad: true })}><img src="img/app/join-room-long.png" className="btn" alt="" /></a>
                </div>
              </div>
            </div>

          </div>
        </div>


        <div className="home-nav">
          <img src="img/app/nav-di.png" className="full-width pos-abs di" alt="" />
          <div className="pure-g text-center">
            <div className="pure-u-1-4">
              <a href={this.props.hallPage}><img src="img/app/nav-mall.png" className="btn" alt=""/></a>
            </div>
            <div className="pure-u-1-4">
              <a href={this.props.clubUrl}><img src="img/app/lower-club.png" className="btn" alt="" /></a>
            </div>
            <div className="pure-u-1-4">
              {/*<img src="img/app/nav-selected.png" className="nav-selected" alt="" />*/}
              <NavLink to="/"><img src="img/app/nav-home.png" className="btn" alt="" /></NavLink>
            </div>
            <div className="pure-u-1-4">
              <NavLink to="/UserCenter"><img src="img/app/nav-my.png" className="btn" alt="" /></NavLink>
            </div>
          </div>
        </div>
        {
          this.props.showCreateGame ? <CreateGameBase currentGame={this.props.currentGame}></CreateGameBase> : null
        }
        {
          this.state.showNumberPad ? <NumberPad close={() => this.setState({ showNumberPad: false })}></NumberPad> : null
        }
        {
          showJoinRule ? <JoinRuleDialog close={() => this.setState({ showJoinRule: false })}></JoinRuleDialog> : null
        }
        {
          this.state.showUploadQrcodeDialog ? 
          <div className="app-qrcode-dialog-wrapper upload-qrcode-wrapper">
          <div className="qrcode-dialog">
          <div className="description">上传头像</div>
          <img onClick={this.closeQrcode.bind(this)} className="qrcode-close" src="img/mall/dialog/close.png" alt=""/>
            
            <div className="upload-actions">
              <input class="file-input" type="file" name="upload-qrcode"  id="upload-qrcode" accept="image/*"  onChange={this.onUploadChange.bind(this)}/>
              <button>
                <span>上传头像</span>
              </button>
            </div>
          </div>
        </div> : null 
      }
      </div>
    )
  }

}

//通过react-redux提供的connect方法将我们需要的state中的数据和actions中的方法绑定到props上
const connectedApp = connect(mapStateToProps, mapDispatchToProps)(App)
export default connectedApp